package com.tao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tao.dao.UserMapper;
import com.tao.entity.User;
import com.tao.enums.AppHttpCodeEnum;
import com.tao.exception.SystemException;
import com.tao.service.UserService;
import com.tao.utils.BeanCopyUtils;
import com.tao.vo.ResponseResult;
import com.tao.vo.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * (User)表服务实现类
 *
 * @author 季伟
 * @since 2023-05-03 20:03:30
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    PasswordEncoder passwordEncoder;
    @Override
    public User getByUserId(Long userId) {
        User user = this.baseMapper.getUserInfo(userId);
        if (user != null) {
            return user;
        }
        return null;
    }

    @Override
    public ResponseResult register(User user) {
        if(!isInfoReady(user)){
            throw new SystemException(AppHttpCodeEnum.BAD_REQUEST,"注册信息填写不全");
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,user.getUserName());
        if(count(queryWrapper)>0){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        save(user);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult selectByUserId(Long userId) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId,userId);
        User user = getOne(queryWrapper);
        Integer balance = user.getBalance();
        return ResponseResult.okResult(balance);
    }

    @Override
    public ResponseResult topUp(Long userId, Integer money) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId,userId);
        User user = getOne(queryWrapper);
        user.setBalance(user.getBalance()+money);
        updateById(user);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getUserInfoById(Long id) {
        User user = getByUserId(id);
        if (user == null)return ResponseResult.errorResult(AppHttpCodeEnum.BAD_REQUEST,"查询不到该用户");
        UserInfoVo infoVo = BeanCopyUtils.copyBean(user,UserInfoVo.class);
        return ResponseResult.okResult(infoVo);
    }


    private boolean isInfoReady(User user){
        return StringUtils.hasText(user.getUserName()) &&
                StringUtils.hasText(user.getPassword());

    }
}

